package cluster

import (
	"encoding/json"
	"fmt"
	"log"
	"reflect"
	"strconv"
	"sync"

	"gitee.com/nggs/protoactor-go/actor"

	"github.com/coreos/etcd/clientv3"
	"github.com/coreos/etcd/mvcc/mvccpb"

	myactor "gitee.com/nggs/actor"
	"gitee.com/nggs/debug"
	etcdv3 "gitee.com/nggs/etcd/v3"
	mylog "gitee.com/nggs/log"
	"gitee.com/nggs/microservice/service"
)

const (
	etcdLeaseTimeoutSec = 5
)

var C = NewCluster(nil, etcdv3.SC)

type WatchCallback func(section string, serviceName string, serviceID int, ev *clientv3.Event, err error)

type Cluster struct {
	myactor.ISuper

	startedWg sync.WaitGroup
	stoppedWg sync.WaitGroup

	etcdConfig EtcdConfig
	etcdsc     *etcdv3.SimpleClient
	leaseID    clientv3.LeaseID
	keepLiveCh <-chan *clientv3.LeaseKeepAliveResponse

	serviceGroups           sync.Map // serviceName -> Group
	globalConfigReflectType reflect.Type
	globalConfig            IGlobalConfig
	globalConfigData        []byte
	watchCallbacks          []WatchCallback
}

func NewCluster(logger mylog.ILogger, etcdsc *etcdv3.SimpleClient) (c *Cluster) {
	c = &Cluster{
		etcdsc: etcdsc,
	}
	if c.etcdsc == nil {
		c.etcdsc = etcdv3.NewSimpleClient()
	}
	c.ISuper = myactor.NewSuper(logger, &c.startedWg, &c.stoppedWg).
		WithOnReceiveMessageHandler(c.onReceiveMessage).
		WithOnStartedHandler(c.onStarted).
		WithOnStoppingHandler(c.onStopping)
	return
}

type ServiceGroupInfo struct {
	GlobalConfig service.IGlobalConfig
	Config       service.IConfig
}

type ServiceGroupInfoMap = map[string]ServiceGroupInfo

func (c *Cluster) Init(etcdConfigFilePath string, globalConfig IGlobalConfig, serviceConfigInfoMap ServiceGroupInfoMap) (err error) {
	err = c.etcdConfig.Load(etcdConfigFilePath)
	if err != nil {
		return
	}

	err = c.etcdConfig.Check()
	if err != nil {
		return
	}

	err = c.etcdsc.Init(c.etcdConfig.Endpoint)
	if err != nil {
		return
	}

	c.leaseID, err = c.etcdsc.GrantLease(etcdLeaseTimeoutSec)
	if err != nil {
		return err
	}

	c.keepLiveCh, err = c.etcdsc.KeepAliveLease(c.leaseID)
	if err != nil {
		return err
	}

	if globalConfig != nil {
		err = c.registerGlobalConfig(globalConfig)
		if err != nil {
			return
		}
	}

	for serviceName, serviceGroupInfo := range serviceConfigInfoMap {
		err = c.registerServiceGroup(serviceName, serviceGroupInfo.GlobalConfig, serviceGroupInfo.Config)
		if err != nil {
			return
		}
	}

	err = c.loadAndCheckConfig()
	if err != nil {
		return
	}

	err = c.Start(nil, "cluster")
	if err != nil {
		return
	}

	c.WaitForStarted()

	return
}

func (c *Cluster) registerGlobalConfig(globalConfig IGlobalConfig) (err error) {
	if c.globalConfigReflectType != nil {
		err = fmt.Errorf("globalConfig config already exist")
		return
	}

	if globalConfig != nil {
		c.globalConfigReflectType = reflect.TypeOf(globalConfig).Elem()
	}

	return
}

func (c *Cluster) registerServiceGroup(serviceName string, globalConfig service.IGlobalConfig, config service.IConfig) (err error) {
	if serviceName == "" {
		err = fmt.Errorf("service group serviceName can not be empty")
		return
	}

	if _, ok := c.serviceGroups.Load(serviceName); ok {
		err = fmt.Errorf("service group [%s] already exist", serviceName)
		return
	}

	if config == nil {
		err = fmt.Errorf("service group [%s] config can not be nil", serviceName)
		return
	}

	sg := service.NewGroup(serviceName)

	if globalConfig != nil {
		sg.GlobalConfigReflectType = reflect.TypeOf(globalConfig).Elem()
	}

	sg.ConfigReflectType = reflect.TypeOf(config).Elem()

	c.serviceGroups.Store(serviceName, sg)

	return
}

func (c *Cluster) loadAndCheckConfig() error {
	var Err error

	if c.globalConfig != nil {
		k := c.GenGlobalConfigKey()
		v, err := c.etcdsc.Get(k)
		if err != nil {
			Err = fmt.Errorf("get globalConfig config fail, key=[%s], %s", k, err)
			return Err
		}
		if len(v) > 0 {
			c.globalConfig = reflect.New(c.globalConfigReflectType).Interface().(service.IGlobalConfig)
			if err := json.Unmarshal(v, c.globalConfig); err != nil {
				Err = fmt.Errorf("unmarshal [%s] json [%s] fail, %s", k, v, err)
				return Err
			}
			if err := c.globalConfig.Check(); err != nil {
				Err = fmt.Errorf("check globalConfig config fail, %v", err)
				return Err
			}
			c.globalConfigData = v
		}
	}

	c.serviceGroups.Range(func(key, value interface{}) bool {
		sg := value.(*service.Group)

		if sg.GlobalConfigReflectType != nil {
			k := c.GenConfigKeyS(sg.Name, service.GlobalConfigServiceID)
			v, err := c.etcdsc.Get(k)
			if err != nil {
				Err = fmt.Errorf("get config [%s] fail, %s", k, err)
				return false
			}

			if len(v) > 0 {
				sg.GlobalConfig = reflect.New(sg.GlobalConfigReflectType).Interface().(service.IGlobalConfig)
				if err := json.Unmarshal(v, sg.GlobalConfig); err != nil {
					Err = fmt.Errorf("unmarshal [%s] json [%s] fail, %s", k, v, err)
					return false
				}
				if err := sg.GlobalConfig.Check(); err != nil {
					Err = fmt.Errorf("check %s globalConfig config fail, %v", sg.Name, err)
					return false
				}
				sg.GlobalConfigData = v
			}
		}

		configPrefix := c.GenConfigKeyPrefix(sg.Name)
		cfgs, err := c.etcdsc.GetStrings(configPrefix)
		if err != nil {
			Err = err
			return false
		}

		var id int
		for k, v := range cfgs {
			_, err := fmt.Sscanf(k, configPrefix+":%d", &id)
			if err != nil {
				continue
			}

			if sg.GetConfigByID(id) != nil {
				Err = fmt.Errorf("duplicate %s[%d] config", sg.Name, id)
				return false
			}

			configData := []byte(v)

			iConfig := reflect.New(sg.ConfigReflectType).Interface()
			if err = json.Unmarshal(configData, iConfig); err != nil {
				Err = fmt.Errorf("unmarshal [%s] json [%s] fail, %s", k, v, err)
				return false
			}

			s := service.NewInfo(iConfig.(service.IConfig), configData, id)
			if s.Config.ID() != id {
				Err = fmt.Errorf("cfg.ID()[%d] != id[%d]", s.Config.ID(), id)
				return false
			}

			if err := s.Config.Check(); err != nil {
				Err = err
				return false
			}

			// 获取实例
			instance, err := c.DirectGetInstance(sg.Name, id)
			if err == nil && !instance.IsEmpty() {
				s.Instance = service.NewInstance()
				*s.Instance = instance

				payload, err := c.DirectGetPayload(sg.Name, id)
				if err != nil {
					// 能取到实例必然能取到负载
					Err = err
					return false
				}
				s.Payload = payload
			}

			sg.AddInfo(id, s)
		}

		c.serviceGroups.Store(sg.Name, sg)

		return true
	})

	return Err
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (c Cluster) GenGlobalConfigKey() string {
	return GenKey(c.EtcdConfig().Root, SectionConfig, "globalConfig")
}

func (c Cluster) GenConfigKeyPrefix(serviceName string) string {
	return GenKey(c.EtcdConfig().Root, SectionConfig, serviceName)
}

func (c Cluster) GenConfigKeyS(serviceName string, strServiceID string) string {
	return GenKey(c.GenConfigKeyPrefix(serviceName), strServiceID)
}

func (c Cluster) GenConfigKey(serviceName string, serviceID int) string {
	return GenKey(c.GenConfigKeyPrefix(serviceName), serviceID)
}

func (c Cluster) ParseConfigKeyS(key string) (serviceName string, strServiceID string, err error) {
	var section string
	_, section, serviceName, strServiceID, err = ParseKeyS(key)
	if err != nil {
		return
	}
	if section != SectionConfig {
		err = fmt.Errorf("ParseConfigKey fail, not config")
		return
	}
	return
}

func (c Cluster) ParseConfigKey(key string) (serviceName string, serviceID int, err error) {
	var strServiceID string
	serviceName, strServiceID, err = c.ParseConfigKeyS(key)
	if err != nil {
		return
	}
	if strServiceID != "" {
		serviceID, err = strconv.Atoi(strServiceID)
	}
	return
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (c Cluster) GenInstanceKeyPrefix(serviceName string) string {
	return GenKey(c.EtcdConfig().Root, SectionInstance, serviceName)
}

func (c Cluster) GenInstanceKey(serviceName string, serviceID int) string {
	return GenKey(c.GenInstanceKeyPrefix(serviceName), serviceID)
}

func (c Cluster) GenInstanceKeyS(serviceName string, strServiceID string) string {
	return GenKey(c.GenInstanceKeyPrefix(serviceName), strServiceID)
}

func (c Cluster) ParseInstanceKey(key string) (serviceName string, serviceID int, err error) {
	var strServiceID string
	serviceName, strServiceID, err = c.ParseInstanceKeyS(key)
	if err != nil {
		return
	}
	serviceID, err = strconv.Atoi(strServiceID)
	return
}

func (c Cluster) ParseInstanceKeyS(key string) (serviceName string, strServiceID string, err error) {
	var section string
	_, section, serviceName, strServiceID, err = ParseKeyS(key)
	if err != nil {
		return
	}
	if section != SectionInstance {
		err = fmt.Errorf("not instance")
		return
	}
	return
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (c Cluster) GenPayloadKeyPrefix(serviceName string) string {
	return GenKey(c.EtcdConfig().Root, SectionPayload, serviceName)
}

func (c Cluster) GenPayloadKey(serviceName string, serviceID int) string {
	return GenKey(c.GenPayloadKeyPrefix(serviceName), serviceID)
}

func (c Cluster) GenPayloadKeyS(serviceName string, strServiceID string) string {
	return GenKey(c.GenPayloadKeyPrefix(serviceName), strServiceID)
}

func (c Cluster) ParsePayloadKey(key string) (serviceName string, serviceID int, err error) {
	var strServiceID string
	serviceName, strServiceID, err = c.ParsePayloadKeyS(key)
	if err != nil {
		return
	}
	serviceID, err = strconv.Atoi(strServiceID)
	return
}

func (c Cluster) ParsePayloadKeyS(key string) (serviceName string, strServiceID string, err error) {
	var section string
	_, section, serviceName, strServiceID, err = ParseKeyS(key)
	if err != nil {
		return
	}
	if section != SectionPayload {
		err = fmt.Errorf("not payload")
		return
	}
	return
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (c *Cluster) DirectGetInstance(serviceName string, serviceID int) (instance service.Instance, err error) {
	key := c.GenInstanceKey(serviceName, serviceID)
	value, err := c.etcdsc.Get(key)
	if err != nil {
		return
	}
	err = json.Unmarshal(value, &instance)
	if err != nil {
		return
	}
	return
}

func (c *Cluster) DirectPutInstance(serviceName string, serviceID int, instance service.Instance) error {
	key := c.GenInstanceKey(serviceName, serviceID)
	value, err := json.Marshal(instance)
	if err != nil {
		return err
	}
	err = c.etcdsc.PutWithLease(key, string(value), c.LeaseID())
	if err != nil {
		return err
	}
	return nil
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (c *Cluster) DirectGetPayload(serviceName string, serviceID int) (payload int, err error) {
	key := c.GenPayloadKey(serviceName, serviceID)
	value, err := c.etcdsc.GetString(key)
	if err != nil {
		return
	}
	payload, err = strconv.Atoi(value)
	if err != nil {
		return
	}
	return
}

func (c *Cluster) DirectPutPayload(serviceName string, serviceID int, payload int) (err error) {
	key := c.GenPayloadKey(serviceName, serviceID)
	value := strconv.Itoa(payload)
	err = c.etcdsc.PutWithLease(key, string(value), c.LeaseID())
	if err != nil {
		return
	}
	return
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (c *Cluster) Close() {
	c.Stop()
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (c *Cluster) onReceiveMessage(ctx actor.Context) {
	defer func() {
		if r := recover(); r != nil {
			c.Error("%v\n%s", r, debug.Stack())
			panic(r)
		}
	}()

	sender := ctx.Sender()
	switch msg := ctx.Message().(type) {
	case *C2S_GlobalConfig:
		send := Get_S2C_GlobalConfig()
		defer func() {
			if sender != nil {
				ctx.Send(sender, send)
			}
		}()

		if len(c.globalConfigData) > 0 {
			send.ConfigData = make([]byte, len(c.globalConfigData))
			copy(send.ConfigData, c.globalConfigData)
		}

	case *C2S_ServiceGlobalConfig:
		send := Get_S2C_ServiceGlobalConfig()
		defer func() {
			if sender != nil {
				ctx.Send(sender, send)
			}
		}()

		sg := c.getServiceGroup(msg.Name)
		if sg == nil {
			send.Err.Code = EC_ServiceGroupNotExist
		} else {
			if len(sg.GlobalConfigData) > 0 {
				send.ConfigData = make([]byte, len(sg.GlobalConfigData))
				copy(send.ConfigData, sg.GlobalConfigData)
			}
		}

	case *C2S_ServiceInfo:
		send := Get_S2C_ServiceInfo()
		defer func() {
			if sender != nil {
				ctx.Send(sender, send)
			}
		}()

		sg := c.getServiceGroup(msg.Name)
		if sg == nil {
			send.Err.Code = EC_ServiceGroupNotExist
		} else {
			info := sg.GetInfoByID(int(msg.ID))
			if info == nil || info.IsEmpty() {
				send.Err.Code = EC_ServiceInfoNotExist
			} else {
				send.Info.CopyFrom(info)
			}
		}

	case *C2S_ServiceInstance:
		send := Get_S2C_ServiceInstance()
		defer func() {
			if sender != nil {
				ctx.Send(sender, send)
			}
		}()

		sg := c.getServiceGroup(msg.Name)
		if sg == nil {
			send.Err.Code = EC_ServiceGroupNotExist
		} else {
			info := sg.GetInfoByID(int(msg.ID))
			if info == nil || info.IsEmpty() {
				send.Err.Code = EC_ServiceInfoNotExist
			} else {
				send.Instance.CopyFrom(info.Instance)
			}
		}

	case *C2S_ServicePayload:
		send := Get_S2C_ServicePayload()
		defer func() {
			if sender != nil {
				ctx.Send(sender, send)
			}
		}()

		sg := c.getServiceGroup(msg.Name)
		if sg == nil {
			send.Err.Code = EC_ServiceGroupNotExist
		} else {
			info := sg.GetInfoByID(int(msg.ID))
			if info == nil || info.IsEmpty() {
				send.Err.Code = EC_ServiceInfoNotExist
			} else {
				send.Payload = int32(info.Payload)
			}
		}

	case *C2S_PutServiceInstance:
		send := Get_S2C_PutServiceInstance()
		defer func() {
			if sender != nil {
				ctx.Send(sender, send)
			}
		}()

		sg := c.getServiceGroup(msg.Name)
		if sg == nil {
			send.Err.Code = EC_ServiceGroupNotExist
		} else {
			info := sg.GetInfoByID(int(msg.ID))
			if info == nil || info.IsEmpty() {
				send.Err.Code = EC_ServiceInfoNotExist
			} else {
				instance := service.NewInstance()
				msg.Instance.DumpTo(instance)

				key := c.GenInstanceKey(msg.Name, int(msg.ID))
				value, err := json.Marshal(instance)
				if err != nil {
					send.Err.Code = EC_MarshalInstanceFail
					send.Err.Message = err.Error()
					return
				}

				err = c.etcdsc.PutWithLease(key, string(value), c.LeaseID())
				if err != nil {
					send.Err.Code = EC_Fail
					send.Err.Message = err.Error()
					return
				}

				info.Instance = instance

				return
			}
		}

	case *C2S_TryLockServicePosition:
		send := Get_S2C_TryLockServicePosition()
		defer func() {
			if sender != nil {
				ctx.Send(sender, send)
			}
		}()

		sg := c.getServiceGroup(msg.Name)
		if sg == nil {
			send.Err.Code = EC_ServiceGroupNotExist
		} else {
			info := sg.GetInfoByID(int(msg.ID))
			if info == nil || info.IsEmpty() {
				send.Err.Code = EC_ServiceInfoNotExist
			} else {
				if info.Instance != nil {
					send.Err.Code = EC_ServiceInstanceAlreadyExist
					return
				}

				instance := service.NewInstance()
				msg.Instance.DumpTo(instance)

				key := c.GenInstanceKey(msg.Name, int(msg.ID))
				value, err := json.Marshal(instance)
				if err != nil {
					send.Err.Code = EC_MarshalInstanceFail
					send.Err.Message = err.Error()
					return
				}

				err = c.etcdsc.PutWithLease(key, string(value), c.LeaseID())
				if err != nil {
					send.Err.Code = EC_Fail
					send.Err.Message = err.Error()
					return
				}

				// todo 目前还未做负载均衡，写死0
				key = c.GenPayloadKey(msg.Name, int(msg.ID))
				err = c.etcdsc.PutWithLease(key, "0", c.LeaseID())
				if err != nil {
					send.Err.Code = EC_Fail
					send.Err.Message = err.Error()
				}

				info.Instance = instance
			}
		}

	case *C2S_PutServicePayload:
		send := Get_S2C_PutServicePayload()
		defer func() {
			if sender != nil {
				ctx.Send(sender, send)
			}
		}()

		sg := c.getServiceGroup(msg.Name)
		if sg == nil {
			send.Err.Code = EC_ServiceGroupNotExist
		} else {
			info := sg.GetInfoByID(int(msg.ID))
			if info == nil || info.IsEmpty() {
				send.Err.Code = EC_ServiceInfoNotExist
			} else {
				key := c.GenPayloadKey(msg.Name, int(msg.ID))
				value := strconv.Itoa(int(msg.Payload))
				err := c.etcdsc.PutWithLease(key, value, c.LeaseID())
				if err != nil {
					send.Err.Code = EC_PutPayloadToEtcdFail
					send.Err.Message = err.Error()
					return
				}

				info.Payload = int(msg.Payload)
			}
		}

	case *C2S_ServiceGroupAllInfo:
		send := Get_S2C_ServiceGroupAllInfo()
		defer func() {
			if sender != nil {
				ctx.Send(sender, send)
			}
		}()

		sg := c.getServiceGroup(msg.Name)
		if sg == nil {
			send.Err.Code = EC_ServiceGroupNotExist
		} else {
			sg.EachInfo(func(id int, i *service.Info) bool {
				info := Get_ServiceInfo()
				info.CopyFrom(i)
				send.Infos = append(send.Infos, info)
				return true
			})
		}

	case *C2S_RoundRobinPickServiceInstance:
		send := Get_S2C_RoundRobinPickServiceInstance()
		defer func() {
			if sender != nil {
				ctx.Send(sender, send)
			}
		}()

		sg := c.getServiceGroup(msg.Name)
		if sg == nil {
			send.Err.Code = EC_ServiceInfoNotExist
		} else {
			info := sg.RoundRobinPickInstance()
			if info != nil {
				send.Info.CopyFrom(info)
			}
		}

	case *C2S_AddWatchCallback:
		send := &S2C_AddWatchCallback{}
		defer func() {
			if sender != nil {
				ctx.Send(sender, send)
			}
		}()
		c.watchCallbacks = append(c.watchCallbacks, msg.cb)

	case *clientv3.Event:
		_, section, serviceName, serviceID, err := ParseKey(string(msg.Kv.Key))
		defer func() {
			for _, cb := range c.watchCallbacks {
				if cb != nil {
					cb(section, serviceName, serviceID, msg, err)
				}
			}
		}()

		if err != nil {
			log.Println(err)
			return
		}

		if serviceName == GlobalConfigName {
			if c.globalConfig == nil {
				err = fmt.Errorf("global config not exist")
				return
			}

			switch section {
			case SectionConfig:
				switch msg.Type {
				case mvccpb.PUT:
					iGlobalConfig := reflect.New(c.globalConfigReflectType).Interface()
					if err = json.Unmarshal(msg.Kv.Value, iGlobalConfig); err != nil {
						err = fmt.Errorf("unmarshal globalConfig config json [%s] fail, %v", string(msg.Kv.Value), err)
						return
					}

					c.globalConfig = iGlobalConfig.(service.IGlobalConfig)

				case mvccpb.DELETE:
					if c.globalConfig == nil {
						err = fmt.Errorf("globalConfig config not exist")
						return
					}
					c.globalConfig = nil
				}

			default:
				err = fmt.Errorf("unsupported globalConfig config section[%s]", section)
			}
			return
		}

		sg := c.getServiceGroup(serviceName)
		if sg == nil {
			err = fmt.Errorf("get Info unit [%s] fail", serviceName)
			return
		}

		switch section {
		case SectionConfig:
			switch msg.Type {
			case mvccpb.PUT:
				iConfig := reflect.New(sg.ConfigReflectType).Interface()
				if err = json.Unmarshal(msg.Kv.Value, iConfig); err != nil {
					err = fmt.Errorf("unmarshal [%s] json [%s] fail, %v", serviceName, string(msg.Kv.Value), err)
					return
				}

				s := sg.GetInfoByID(serviceID)
				if s == nil {
					s = service.NewInfo(iConfig.(service.IConfig), msg.Kv.Value, serviceID)
					if s.Config.ID() != serviceID {
						err = fmt.Errorf("%s cfg.ID()[%d] != id[%d]", serviceName, s.Config.ID(), serviceID)
						return
					}
					err = s.Config.Check()
					if err != nil {
						return
					}
					sg.AddInfo(serviceID, s)
				} else {
					s.Config = iConfig.(service.IConfig)
				}

			case mvccpb.DELETE:
				sg.RemoveInfo(serviceID)
			}

		case SectionInstance:
			s := sg.GetInfoByID(serviceID)
			if s == nil {
				err = fmt.Errorf("get Info %s[%d] fail", serviceName, serviceID)
				return
			}

			switch msg.Type {
			case mvccpb.PUT:
				instance := service.NewInstance()
				if err = json.Unmarshal(msg.Kv.Value, instance); err != nil {
					err = fmt.Errorf("put %s[%d] instance fail, unmarshal [%s] fail, %v",
						serviceName, serviceID, string(msg.Kv.Value), err)
					return
				}
				// 服务启动时会put一个空的instance来占位，所以需要避免添加一个空的instance
				if instance.IsEmpty() {
					err = fmt.Errorf("can not put a %s[%d] nil instance", serviceName, serviceID)
					return
				}
				s.Instance = instance

			case mvccpb.DELETE:
				if s.Instance == nil {
					err = fmt.Errorf("already delete %s[%d] instance fail", serviceName, serviceID)
					return
				}
				s.Instance = nil
			}

		case SectionPayload:
			s := sg.GetInfoByID(serviceID)
			if s == nil {
				err = fmt.Errorf("get Info %s[%d] fail", serviceName, serviceID)
				return
			}

			switch msg.Type {
			case mvccpb.PUT:
				if s.Instance == nil {
					err = fmt.Errorf("put %s[%d] payload fail, instance is nil", serviceName, serviceID)
					return
				}
				s.Payload, err = strconv.Atoi(string(msg.Kv.Value))
				if err != nil {
					s.Payload = service.PayloadNil
					err = fmt.Errorf("put %s[%d] payload fail, %v", serviceName, serviceID, err)
					return
				}

			case mvccpb.DELETE:
				if s.Payload == service.PayloadNil {
					err = fmt.Errorf("already delete %s[%d] payload", serviceName, serviceID)
					return
				}
				s.Payload = service.PayloadNil
			}

		default:
			err = fmt.Errorf("unsupported section[%s]", section)
		}

	default:
		c.Error("recv unsupported msg [%#v] from [%v]", msg, sender)
	}
}

func (c *Cluster) onStarted(ctx actor.Context) {
	// 开启监听etcd的协程
	rch := c.etcdsc.WatchWithPrefix(c.etcdConfig.Root)
	var wg sync.WaitGroup
	wg.Add(1)
	go etcdv3.WatchLoop(rch, func(ev *clientv3.Event) {
		myactor.RootContext.Send(c.PID(), ev)
	}, &wg)
	wg.Wait()
}

func (c *Cluster) onStopping(ctx actor.Context) {
	c.etcdsc.Close()
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (c Cluster) EtcdConfig() EtcdConfig {
	return c.etcdConfig
}

func (c Cluster) LeaseID() clientv3.LeaseID {
	return c.leaseID
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (c Cluster) GetGlobalConfig() (IGlobalConfig, error) {
	recv, err := Request_S2C_GlobalConfig(c.PID(), Get_C2S_GlobalConfig())
	if err != nil {
		return nil, err
	}
	if len(recv.ConfigData) == 0 {
		return nil, nil
	}
	globalConfig := reflect.New(c.globalConfigReflectType).Interface().(service.IGlobalConfig)
	err = json.Unmarshal(recv.ConfigData, globalConfig)
	if err != nil {
		return nil, err
	}
	return globalConfig, nil
}

func (c Cluster) getServiceGroup(serviceName string) *service.Group {
	v, ok := c.serviceGroups.Load(serviceName)
	if ok {
		return v.(*service.Group)
	}
	return nil
}

func (c Cluster) GetServiceGlobalConfig(serviceName string) (service.IGlobalConfig, error) {
	sg := c.getServiceGroup(serviceName)
	if sg == nil {
		return nil, fmt.Errorf("service group not exist")
	}

	send := Get_C2S_ServiceGlobalConfig()
	send.Name = serviceName
	recv, err := Request_S2C_ServiceGlobalConfig(c.PID(), send)
	if err != nil {
		return nil, err
	}
	if !recv.Err.IsNil() {
		return nil, recv.Err
	}

	if len(recv.ConfigData) == 0 {
		return nil, nil
	}
	globalConfig := reflect.New(sg.GlobalConfigReflectType).Interface().(service.IGlobalConfig)
	err = json.Unmarshal(recv.ConfigData, globalConfig)
	if err != nil {
		return nil, err
	}
	return globalConfig, nil
}

func (c Cluster) GetServiceInfo(serviceName string, serviceID int) (*service.Info, error) {
	sg := c.getServiceGroup(serviceName)
	if sg == nil {
		return nil, fmt.Errorf("service group not exist")
	}

	send := Get_C2S_ServiceInfo()
	send.Name = serviceName
	send.ID = int32(serviceID)
	recv, err := Request_S2C_ServiceInfo(c.PID(), send)
	if err != nil {
		return nil, err
	}
	if !recv.Err.IsNil() {
		return nil, recv.Err
	}

	if len(recv.Info.ConfigData) == 0 {
		return nil, nil
	}
	config := reflect.New(sg.ConfigReflectType).Interface().(service.IConfig)
	err = json.Unmarshal(recv.Info.ConfigData, config)
	if err != nil {
		return nil, err
	}

	info := service.NewInfo(config, recv.Info.ConfigData, config.ID())
	recv.Info.DumpTo(info)

	return info, nil
}

func (c Cluster) GetServiceInstance(serviceName string, serviceID int) (*service.Instance, error) {
	sg := c.getServiceGroup(serviceName)
	if sg == nil {
		return nil, fmt.Errorf("service group not exist")
	}

	send := Get_C2S_ServiceInstance()
	send.Name = serviceName
	send.ID = int32(serviceID)
	recv, err := Request_S2C_ServiceInstance(c.PID(), send)
	if err != nil {
		return nil, err
	}
	if !recv.Err.IsNil() {
		return nil, recv.Err
	}

	instance := service.NewInstance()
	recv.Instance.DumpTo(instance)
	return instance, nil
}

func (c Cluster) PutServiceInstance(serviceName string, serviceID int, instance *service.Instance) error {
	sg := c.getServiceGroup(serviceName)
	if sg == nil {
		return fmt.Errorf("service group not exist")
	}

	send := Get_C2S_PutServiceInstance()
	send.Name = serviceName
	send.ID = int32(serviceID)
	send.Instance.CopyFrom(instance)
	recv, err := Request_S2C_PutServiceInstance(c.PID(), send)
	if err != nil {
		return err
	}
	if !recv.Err.IsNil() {
		return recv.Err
	}

	return nil
}

func (c Cluster) TryLockServicePosition(serviceName string, serviceID int, instance *service.Instance) error {
	sg := c.getServiceGroup(serviceName)
	if sg == nil {
		return fmt.Errorf("service group not exist")
	}

	send := Get_C2S_TryLockServicePosition()
	send.Name = serviceName
	send.ID = int32(serviceID)
	send.Instance.CopyFrom(instance)
	recv, err := Request_S2C_TryLockServicePosition(c.PID(), send)
	if err != nil {
		return err
	}
	if !recv.Err.IsNil() {
		return recv.Err
	}

	return nil
}

func (c *Cluster) RoundRobinPickServiceInstance(serviceName string) (info *service.Info, err error) {
	sg := c.getServiceGroup(serviceName)
	if sg == nil {
		return nil, fmt.Errorf("service group not exist")
	}

	send := Get_C2S_RoundRobinPickServiceInstance()
	send.Name = serviceName
	recv, err := Request_S2C_RoundRobinPickServiceInstance(c.PID(), send)
	if err != nil {
		return nil, err
	}
	if !recv.Err.IsNil() {
		return nil, recv.Err
	}
	if recv.Info == nil || len(recv.Info.ConfigData) == 0 {
		return nil, nil
	}

	config := reflect.New(sg.ConfigReflectType).Interface().(service.IConfig)
	err = json.Unmarshal(recv.Info.ConfigData, config)
	if err != nil {
		return nil, err
	}

	info = service.NewInfo(config, recv.Info.ConfigData, config.ID())
	recv.Info.DumpTo(info)
	return
}

func (c Cluster) GetServicePayload(serviceName string, serviceID int) (int, error) {
	sg := c.getServiceGroup(serviceName)
	if sg == nil {
		return service.PayloadNil, fmt.Errorf("service group not exist")
	}

	send := Get_C2S_ServicePayload()
	send.Name = serviceName
	send.ID = int32(serviceID)
	recv, err := Request_S2C_ServicePayload(c.PID(), send)
	if err != nil {
		return service.PayloadNil, err
	}
	if !recv.Err.IsNil() {
		return service.PayloadNil, recv.Err
	}

	return int(recv.Payload), nil
}

func (c Cluster) PutServicePayload(serviceName string, serviceID int, payload int) error {
	sg := c.getServiceGroup(serviceName)
	if sg == nil {
		return fmt.Errorf("service group not exist")
	}

	send := Get_C2S_PutServicePayload()
	send.Name = serviceName
	send.ID = int32(serviceID)
	send.Payload = int32(payload)
	recv, err := Request_S2C_PutServicePayload(c.PID(), send)
	if err != nil {
		return err
	}
	if !recv.Err.IsNil() {
		return recv.Err
	}

	return nil
}

func (c Cluster) GetServiceGroupAllInfo(serviceName string) ([]*service.Info, error) {
	sg := c.getServiceGroup(serviceName)
	if sg == nil {
		return nil, fmt.Errorf("service group not exist")
	}

	send := Get_C2S_ServiceGroupAllInfo()
	send.Name = serviceName
	recv, err := Request_S2C_ServiceGroupAllInfo(c.PID(), send)
	if err != nil {
		return nil, err
	}
	if !recv.Err.IsNil() {
		return nil, recv.Err
	}

	var infos []*service.Info
	for _, i := range recv.Infos {
		if len(i.ConfigData) == 0 {
			continue
		}
		config := reflect.New(sg.ConfigReflectType).Interface().(service.IConfig)
		err = json.Unmarshal(i.ConfigData, config)
		if err != nil {
			return nil, err
		}

		info := service.NewInfo(config, i.ConfigData, config.ID())
		i.DumpTo(info)
		infos = append(infos, info)
	}

	return infos, nil
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (c *Cluster) AddWatchCallback(cb WatchCallback) (err error) {
	if cb == nil {
		return fmt.Errorf("callback is nil")
	}
	send := &C2S_AddWatchCallback{}
	send.cb = cb
	recv, err := Request_S2C_AddWatchCallback(c.PID(), send)
	if err != nil {
		return err
	}
	if recv.err != nil {
		return recv.err
	}
	return
}
